package com.example.resourceSharingPlatform.controller;


import com.example.resourceSharingPlatform.config.security.jwt.JwtTokenUtils;
import com.example.resourceSharingPlatform.entity.Item;

import com.example.resourceSharingPlatform.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Autowired
    private HttpServletRequest request;
    /**
     * 1.通过id查询item信息 GET
     * ip:port/itemId?id=xx
     *
     * 2.通过name查询item信息 GET
     * ip:port/itemName?name=xxx
     *
     * 3.查询所有item信息 GET
     * ip:port/items
     *
     * 4.通过type查询item信息 GET
     * ip:port/itemType?type=xxx
     *
     * 5.添加item信息 POST
     * ip:port/item
     * body中填写item类的信息
     *
     * 6.根据id删除item DELETE
     * ip:port/item?id=xx
     *
     * 7.更新item信息 PUT
     * ip:port/item
     * body中填写用户信息
     *
     * 8.根据owner_id查询item信息
     * */

    @GetMapping("/itemId")
    Item getItemById(@RequestParam(value = "id")int id){
        return itemService.queryItemById(id);
    }

    @GetMapping("/itemOwnerId")
    List<Item> getItemByOwnerId(){
        String owner_id = new JwtTokenUtils().getUsernameFromToken(request.getHeader("Authorization"));
        return itemService.queryItemByOwnerId(owner_id);
    }

    @GetMapping("/itemBorrowState")
    List<Item> getItemByBorrowState(@RequestParam(value="borrow_state")String borrow_state,
                                    @RequestParam(value="type")String type){
        return itemService.queryItemByBorrowState(borrow_state, type);
    }

    @GetMapping("/itemName")
    List<Item> getItemByName(@RequestParam(value = "name")String name){
        return itemService.queryItemByName(name);
    }

    @GetMapping("/itemType")
    List<Item> getItemByType(@RequestParam(value = "type")String type){
        return itemService.queryItemByType(type);
    }

    @GetMapping("/items")
    List<Item> getItems(){
        return itemService.queryAll();
    }

    @PostMapping("/item")
    Item addItem(@RequestBody Item item){
        String owner_id = new JwtTokenUtils().getUsernameFromToken(request.getHeader("Authorization"));
        item.setOwner_id(owner_id);
        return itemService.insertItem(item);
    }

    @PutMapping("/item")
    boolean updateItem(@RequestBody Item item){
        return itemService.updateItem(item);
    }

    @DeleteMapping("/item")
    boolean deleteItemById(@RequestBody int id){
        return itemService.deleteItemById(id);
    }
}
